import { onUnmounted, ref } from 'vue'

export function useDebounce<T extends (...args: any[]) => any>(fn: T, delay = 300) {
  const timer = ref<ReturnType<typeof setTimeout> | null>(null)

  // 组件卸载时自动清除定时器
  onUnmounted(() => {
    if (timer.value) clearTimeout(timer.value)
  })

  return function (this: any, ...args: Parameters<T>) {
    if (timer.value) clearTimeout(timer.value)
    timer.value = setTimeout(() => {
      fn.apply(this, args)
      timer.value = null
    }, delay)
  }
}
